﻿using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Zocono.Infrastructure.Common;

namespace Zocono.WMS.Infrastructure.BaseRepository
{
    public class BaseRepository<T> : SimpleClient<T> where T : class, new()
    {
        private ILogUtil _logUtil;
        private static readonly bool recordSql = Convert.ToBoolean(JsonConfigurationHelper.GetJson("appsettings.json", "RecordSql"));

        public BaseRepository(SqlSugarClient context = null) : base(context) //注意这里要有默认值等于null
        {
            if (context == null)
            {
                base.Context = new SqlSugarClient(new ConnectionConfig()
                {
                    DbType = SqlSugar.DbType.SqlServer,
                    InitKeyType = InitKeyType.Attribute,
                    IsAutoCloseConnection = true,
                    ConnectionString = ""
                });
            }

            if (recordSql)
            {
                context.Aop.OnLogExecuting = (sql, pars) =>
               {
                   string strSql = FormatHelper.FormatParam(sql, pars);
                   if (_logUtil == null)
                       _logUtil = new NlogUtil();
                   _logUtil.Info(strSql);
               };
            }
        }

        public void BeginTran()
        {
            Context.Ado.BeginTran();
        }
        public void CommitTran()
        {
            try
            {
                Context.Ado.CommitTran();
            }
            catch (Exception)
            {
                Context.Ado.RollbackTran();
                throw;
            }
        }

    }
}
